/*
 * Copyright (C) 2009 Chang Min Lee <ch5ngmn@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details. (/COPYING)
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "CommBroker.h"

CommBroker::CommBroker()
: is_activated_(false)
{
}

CommBroker::~CommBroker()
{
	if (is_activated())
		close(true);
}

int
CommBroker::open (int argc, ACE_TCHAR* argv [])
{
  this->orb_ = CORBA::ORB_init (argc, argv, ACE_TEXT(""));

	if (CORBA::is_nil (orb_.in())) {
		ACE_ERROR_RETURN ((LM_ERROR, "orb initializing failed\n"), -1);

  }

	if (0 != resolve_naming_service ()) {
		ACE_ERROR_RETURN ((LM_ERROR, "name server locating failed\n"), -1);
	}

	is_activated_ = true;
  return 0;
} 

void
CommBroker::close (bool wait_for_completion)
{
	orb_->shutdown(wait_for_completion);
	orb_->destroy ();

	is_activated_ =false;
}

bool 
CommBroker::is_activated (void) 
{
	return is_activated_;
}

int
CommBroker::resolve_naming_service (void)
{
  CORBA::Object_var naming_object = orb_->resolve_initial_references ("NameService");

  // Need to check return value for errors.
	if (CORBA::is_nil (naming_object.in ()))
	{
		ACE_ERROR_RETURN ((LM_ERROR, "(%P|%t) Unable to resolve the Naming Service.\n"), -1);
	}

  naming_ = CosNaming::NamingContextExt::_narrow (naming_object.in ());

  //@@tmp hack, otherwise crashes on exit!..??
  //CosNaming::NamingContextExt::_duplicate (this->naming_.in());

  return 0;
}

void 
CommBroker::run (void)
{
	orb_->run();
}
  
void 
CommBroker::run (ACE_Time_Value &tv)
{
	orb_->run(tv);
}

void 
CommBroker::run (ACE_Time_Value *tv)
{
	orb_->run(tv);
}


bool 
CommBroker::work_pending (void)
{
	return orb_->work_pending();
}

bool 
CommBroker::work_pending (ACE_Time_Value &tv)
{
	return orb_->work_pending(tv);
}

void 
CommBroker::perform_work (void)
{
	orb_->perform_work();
}

void 
CommBroker::perform_work (ACE_Time_Value &tv)
{
	orb_->perform_work(tv);
}

void 
CommBroker::perform_work (ACE_Time_Value *tv)
{
	orb_->perform_work(tv);
}
